from flask import g
from flask_restful import Resource, reqparse, abort, fields, marshal

from App.apis.api_constant import HTTP_OK
from App.apis.cinema_admin.utils import login_required
from App.models.cinema_admin.cinema_address_model import CinemaAddress
from App.models.cinema_admin.cinema_hall_model import Hall

parse = reqparse.RequestParser()
parse.add_argument("h_num" , required = True , type = int , help = "请提供放映厅编号")
parse.add_argument("h_seats" , required = True , help = "请提供放映厅布局")
parse.add_argument("address_id" , required = True , type = int ,  help = "请提供电影院地址")

hall_fields = {
    "h_num":fields.Integer,
    "h_seats":fields.String,
    "address_id":fields.Integer(attribute="h_address_id")
}
single_hall_fields = {
    "msg":fields.String,
    "status":fields.Integer,
    "data":fields.Nested(hall_fields)
}

class CinemaHallsResource(Resource):
    @login_required
    def post(self):
        args = parse.parse_args()
        h_num = args.get("h_num")
        h_seats = args.get("h_seats")
        address_id = args.get("address_id")

        cinema_addresses = CinemaAddress.query.filter(CinemaAddress.C_user_id == g.user_id)
        cinema_ids = []
        for cinema_address in cinema_addresses:
            cinema_ids.append(cinema_address.id)
        if not address_id in cinema_ids:
            abort(400 , msg = 'error action')

        hall = Hall(h_address_id = address_id , h_num = h_num , h_seats = h_seats)
        if not hall.save():
            abort(400 , msg = '放映厅创建失败')

        # data = {
        #     "msg": "创建成功",
        #     "status": HTTP_OK,
        #     "data": hall
        # }
        # return marshal(data, single_hall_fields)  # 用到Nest的就在return处marshal，普通的就直接在"data"里marshal
        data = {
            "msg":"创建成功",
            "status":HTTP_OK,
            "data":marshal(hall, hall_fields)
        }
        return data



